#pragma once
#include <iostream>
#include <cstring>
#include <cassert>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <functional>
#include <cstdio>
#define NUM 128
namespace ThreadNS
{
    class Thread
    {
        typedef std::function<void *(void *)> func_t;
        // using func_t = function<void*(void*)>;
    public:
        static void *routine(void *args)
        {
            Thread *p = static_cast<Thread *>(args);
            return p->Run();
        }
        Thread()
        {
            // 吧名字创建出来
            char buffer[NUM];
            snprintf(buffer, sizeof(buffer), "thread-%d", ThreadNum++);
            _name = buffer;
        }
        void start(func_t func, void *args = nullptr)
        {
            // 创建线程
            _func = func;
            _args = args;
            int n = pthread_create(&_tid, nullptr, routine, this);
            assert(n == 0);
            (void)n;
        }
        std::string ThreadName()
        {
            return _name;
        }
        ~Thread()
        {
        }
        void join()
        {
            int n = pthread_join(_tid, nullptr);
            assert(n == 0);
            (void)n;
        }
        void *Run()
        {
            return _func(_args);
        }

    private:
        static int ThreadNum;
        std::string _name;
        void *_args;
        func_t _func;
        pthread_t _tid;
    };
    int Thread::ThreadNum = 1;

}
